package com.wen.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wen.apicommon.model.entity.UserInterfaceInfo;
import com.wen.project.common.ErrorCode;
import com.wen.project.exception.BusinessException;
import com.wen.project.mapper.UserInterfaceInfoMapper;
import com.wen.project.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author wenzhaobo
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2024-08-03 14:38:02
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo interfaceInfo, boolean add) {

         Long id = interfaceInfo.getId();
         Long userId = interfaceInfo.getUserId();
         Long interfaceInfoId = interfaceInfo.getInterfaceInfoId();
         Integer totalNum = interfaceInfo.getTotalNum();
         Integer leftNum = interfaceInfo.getLeftNum();
         Integer status = interfaceInfo.getStatus();
         Date createTime = interfaceInfo.getCreateTime();
         Date updateTime = interfaceInfo.getUpdateTime();
         Integer isDelete = interfaceInfo.getIsDelete();

        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建时，所有参数必须非空
        if(add){
           if(interfaceInfoId <= 0 || userId <= 0){
               throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或者用户不存在");
           }
        }
        if(leftNum < 0){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"剩余调用次数不能小于0");
        }
    }

    /**
     * 调用接口统计
     * SQL : update user_interface_info set leftNum = leftNum - 1,totalNum = totalNum + 1 where interfaceInfoId = interfaceInfoId and userId = userId
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(Long interfaceInfoId, Long userId) {
        //校验
        if(interfaceInfoId <= 0 || userId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //todo 加锁 事务处理-涉及到一个加一个减操作
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId",interfaceInfoId);
        updateWrapper.eq("userId",userId);
        updateWrapper.gt("leftNum",0);//剩余调用次数大于0，小于o 则检验失败，在网关层增加一下检查可调用次数即可。
        updateWrapper.eq("isDelete",0);//未删除
        updateWrapper.setSql("leftNum = leftNum - 1,totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }

}




